package fhq.hcmute.edu.vn.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import fhq.hcmute.edu.vn.network.PhoneInfos;

public final class ListDevicesConnected {
	private ListDevicesConnected() {

	}

	private static ArrayList<PhoneInfos> listDataConnections;

	static {
		if (listDataConnections == null) {
			try {
				listDataConnections = getDataConnections();
			} catch (ClassNotFoundException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static ArrayList<PhoneInfos> getListDataConnections() {
		return listDataConnections;
	}

	public static void addDataConnections(final PhoneInfos phoneInfos) {
		if (listDataConnections == null) {
			listDataConnections = new ArrayList<>();
		}
		listDataConnections.add(phoneInfos);
	}

	public static void removeDataConnections(final int pos) {
		if (listDataConnections != null) {
			listDataConnections.remove(pos);
		}
	}

	public static boolean isExists(final PhoneInfos phoneInfos) {
		if (listDataConnections == null) {
			return false;
		}
		for (int i = 0; i < listDataConnections.size(); i++) {
			PhoneInfos infos = listDataConnections.get(i);
			if (infos.equals(phoneInfos)) {
				return true;
			}
		}
		return false;
	}

	public static PhoneInfos get(final int index) {
		if (listDataConnections != null) {
			return listDataConnections.get(index);
		}
		return null;
	}

	public static int getSize() {
		if (listDataConnections != null) {
			return listDataConnections.size();
		}
		return 0;
	}

	/**
	 * Save data to disk.
	 * 
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static void commit() throws IOException {
		File folder = new File("List devices");
		if (!folder.exists()) {
			folder.mkdir();
		}
		File file = new File("List devices/listDevices.ld");
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(
				fileOutputStream);
		objectOutputStream.writeObject(listDataConnections);
		objectOutputStream.close();
	}

	@SuppressWarnings("unchecked")
	private static ArrayList<PhoneInfos> getDataConnections()
			throws IOException, ClassNotFoundException {
		ArrayList<PhoneInfos> listDataConnections = null;
		File file = new File("List devices/listDevices.ld");
		if (file.exists()) { // File is Exists
			listDataConnections = new ArrayList<>();
			FileInputStream fileInputStream = new FileInputStream(file);
			ObjectInputStream objectInputStream = new ObjectInputStream(
					fileInputStream);
			listDataConnections = (ArrayList<PhoneInfos>) objectInputStream
					.readObject();
			objectInputStream.close();
		}
		return listDataConnections;
	}
}
